<?php

namespace common\models;

use Yii;

/**
 * 项目尽调报告-干系人及资产情况
 * This is the model class for table "project_investigation_stakeholder".
 *
 * @property string $id
 * @property string $project_id
 * @property integer $stakeholder_type
 * @property string $stakeholder_title
 * @property string $registered_capital
 * @property string $registered_address
 * @property string $legal_representative
 * @property string $scope_of_business
 * @property string $proportion
 * @property string $borrower
 * @property string $buy_back
 * @property integer $faith
 * @property integer $limit_high
 * @property string $block_list
 * @property string $block_value
 * @property string $guarantee_scope
 * @property string $guarantee
 * @property string $mortgage_order
 * @property string $seal_order
 * @property string $other_mortgage
 * @property string $evaluate_price
 * @property string $auction_price
 * @property string $market_price
 * @property string $rent
 * @property string $live
 * @property string $interview
 * @property string $payment_reservation
 * @property string $reservation_evidence
 * @property string $payment_radical
 * @property string $radical_evidence
 * @property string $created_at
 * @property string $updated_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 *
 * @property string $update_log
 * @property string $other_guarantee
 * @property string $rental_price
 * @property string $identical_price
 * @property string $recently_price
 * @property string $buyer_price
 * @property string $tax_price
 */
class ProjectInvestigationStakeholder extends \yii\db\ActiveRecord
{
    // [1 => '债务人', 2 => '抵押人', 3 => '保证人', 4 => '其他承债人'],
    const STAKEHOLDER_TYPE_BORROWER = 1;
    const STAKEHOLDER_TYPE_MORTGAGOR = 2;
    const STAKEHOLDER_TYPE_GUARANTOR = 3;
    const STAKEHOLDER_TYPE_OTHER = 4;

    //是否列失信
    const FAITH_TRUE = 1;
    const FAITH_FALSE = 2;

    //是否限高
    const LIMIT_HIGH_TRUE = 1;
    const LIMIT_HIGH_FALSE = 2;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_investigation_stakeholder';
    }
    /*关联表investigationLawsuit project_investigation_lawsuit*/
    public  function  getInvestigationLawsuit(){
        return $this->hasMany(ProjectInvestigationLawsuit::className(),['stakeholder_id'=>'id']);
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //[['project_id', 'stakeholder_type','stakeholder_title'], 'required'],
            [['project_id', 'stakeholder_type'], 'required'],
            [['project_id', 'stakeholder_type', 'faith', 'limit_high', 'lock_user'], 'integer'],
            [['scope_of_business', 'proportion', 'borrower', 'buy_back', 'block_value', 'guarantee_scope', 'guarantee', 'mortgage_order', 'seal_order', 'other_mortgage', 'rent', 'live', 'interview', 'reservation_evidence', 'radical_evidence',
                'update_log', 'other_guarantee', 'rental_price', 'identical_price', 'recently_price', 'buyer_price', 'tax_price'], 'trim'],
            [['scope_of_business', 'proportion', 'borrower', 'buy_back', 'block_value', 'guarantee_scope', 'guarantee', 'mortgage_order', 'seal_order', 'other_mortgage', 'rent', 'live', 'interview', 'reservation_evidence', 'radical_evidence',
                'update_log', 'other_guarantee', 'rental_price', 'identical_price', 'recently_price', 'buyer_price', 'tax_price'], 'string'],
            [['created_at', 'updated_at'], 'safe'],

            [['stakeholder_title', 'registered_capital', 'registered_address', 'legal_representative'], 'string', 'max' => 65025],

            [['block_list', 'evaluate_price', 'auction_price', 'market_price', 'payment_reservation',
                'payment_radical', 'lock_timestamp', 'identical_price', 'recently_price', 'buyer_price', 'tax_price'], 'string'/*, 'max' => 255*/],

            ['stakeholder_type', 'in', 'range' => [1, 2, 3, 4]],

            //['interest', 'validateRegisteredCapital'],
        ];
    }

    /*public function validateRegisteredCapital()
    {
        if (!is_numeric($this->interest)) {
            $this->addError('interest', '注册资本必须是数值。');
        }
    }*/

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目',
            'stakeholder_type' => '干系人类型',
            'stakeholder_title' => '干系人名称',
            'registered_capital' => '注册资本',
            'registered_address' => '注册地址',
            'legal_representative' => '法定代表人',
            'scope_of_business' => '经营范围',
            'proportion' => '股东及持股人比例',
            'borrower' => '借款人状况',
            'buy_back' => '和解回购意愿',
            'faith' => '是否列失信',
            'limit_high' => '是否限制高消费',
            'block_list' => '失信名单',
            'block_value' => '列失信价值描述',
            //'guarantee_scope' => '抵押担保范围、保证人保证范围、承债理由及法律依',
            'guarantee_scope' => '保证人保证范围',
            //'guarantee' => '抵押物、承债资产情况',
            'guarantee' => '承债资产详细情况',
            'mortgage_order' => '抵押顺序',
            'seal_order' => '查封顺序',
            'other_mortgage' => '其他抵押、查封详情',
            'evaluate_price' => '评估价',
            'auction_price' => '拍卖价',
            'market_price' => '市场询价',
            'rent' => '租赁情况',
            'live' => '居住情况',
            'interview' => '现场访谈其他情况',
            'payment_reservation' => '回现保守',
            'reservation_evidence' => '保守依据',
            'payment_radical' => '回现激进',
            'radical_evidence' => '激进依据',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',

            'update_log' => '变更记录',
            'other_guarantee' => '抵押物外其他承债资产',
            'identical_price' => '同类型司法拍卖资产价格',
            'recently_price' => '访谈中介最近成交价及快速转让价',
            'buyer_price' => '买家报价',
            'rental_price' => '租金情况及其他可比物业',
            'tax_price' => '税费',
        ];
    }

    /**
     * 获取一个对象
     * @param array $where
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getOne($where = array())
    {
        return ProjectInvestigationStakeholder::find()->where($where)->one();
    }

    /**
     * 获取多个对象
     * @param array $where
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getAll($where = array())
    {
        return ProjectInvestigationStakeholder::find()->where($where)->all();
    }

    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * //@param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module, $type)
    {
        $model = self::findOne((int)$id);
        $project = Project::findOne($project_id);
        if ($model === null || $project === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2 ) {
            $project->type = 1;
        }

        $attributeLabels = $this->attributeLabels();
        $intAttributeLabels = ['project_id', 'stakeholder_type', 'faith', 'limit_high', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if ($value!='') {
                            if (in_array($key, $intAttributeLabels)) {
                                switch ($key) {
                                    case 'project_id':
                                        $value = $project->title;
                                        break;
                                    case 'faith':
                                        $title = Yii::$app->params['faith'];
                                        $value = $title[$value];
                                        break;
                                    case 'limit_high':
                                        $title = Yii::$app->params['limitHigh'];
                                        $value = $title[$value];
                                        break;
                                    case 'stakeholder_type':
                                        $title = Yii::$app->params['stakeholderType'];
                                        $value = $title[$value];
                                        break;
                                    case 'lock_user':
                                        if ($value>0) {
                                            if (isset($userInfo[$value]['description']))
                                                $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                            else
                                                $value = $userInfo[$value]['realname'];
                                        } else {
                                            $value = '';
                                        }
                                        break;
                                    default:
                                }
                            }
                            if ($attributeLabels[$key] != 'ID') {
                                $log .= "{$attributeLabels[$key]}：{$value}\n";
                            }
                        }
                    }
                }
                break;
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    $model->lock_user = null;
                    $model->lock_timestamp = null;
                    if ($model->save()) {
                        return array('state' => true, 'msg' => '保存成功');
                    } else {
                        return array('state' => false, 'msg' => '保存失败');
                    }
                    //return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'faith':
                                    $title = Yii::$app->params['faith'];
                                    $value = $title[$value];
                                    break;
                                case 'limit_high':
                                    $title = Yii::$app->params['limitHigh'];
                                    $value = $title[$value];
                                    break;
                                case 'stakeholder_type':
                                    $title = Yii::$app->params['stakeholderType'];
                                    $value = $title[$value];
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        if (isset($userInfo[$value]['description']))
                                            $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                        else
                                            $value = $userInfo[$value]['realname'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                default:
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type !=2 ) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('项目尽调日志添加失败');
            }

            return array('state' => true, 'msg' => '添加项目尽调修改日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
